
import React from "react";
import Qs from 'qs'
import axios from "../../../../http";
import moment from 'moment';

import Calend, { CalendarView } from 'calend'
import 'calend/dist/styles/index.css';
import {OnNewEventClickData} from "calend";
import {OnEventClickData} from "calend";
import {OnPageChangeData} from "calend";
import {OnSelectViewData} from "calend";

import {withRouter} from "react-router";
import {PRIVATE_ROUTE} from "../../../../route.constants";
class MySchedule extends React.Component{

    constructor(props) {

        super(props);

        this.state={eventList:{},userList:[],userViewList:[],modalVisible:false,modalEditVisible:false,modalViewVisible:false,calendarWeekends:true};

    }
    onNewEventClick = (data: OnNewEventClickData) => {

        this.props.history.push({pathname:"/main/"+PRIVATE_ROUTE.APP_OA_WORK_SCHEDULE_ADD})

    };
    onEventClick = (data: OnEventClickData) => {

        let originEvent=data.originEvent;
        let state={
            id:originEvent.id,
            originId: originEvent.originId,
            userViewList:[],
            title:originEvent.title,
            memo:originEvent.memo,
            startDate:originEvent.originStart.substring(0,10),
            endDate:originEvent.originEnd.substring(0,10),
            startTime:[originEvent.originStart.substring(11,13),originEvent.originStart.substring(14,16)],
            endTime:[originEvent.originEnd.substring(11,13),originEvent.originEnd.substring(14,16)]};
        for(let i=0;i<originEvent.simpleUserList.length;i++){
            let simpleUser=originEvent.simpleUserList[i];
            state.userViewList.push(simpleUser.realName+'_'+simpleUser.id)
        }

        if(originEvent.editAble==true){
            this.props.history.push({pathname:"/main/"+PRIVATE_ROUTE.APP_OA_WORK_SCHEDULE_EDIT,state:state})
        }else {
            this.props.history.push({pathname:"/main/"+PRIVATE_ROUTE.APP_OA_WORK_SCHEDULE_VIEW,state:state})
        }
    };
    onSelectView = (view: OnSelectViewData) => {

    }

    /**
     * this function fix the bug that the Calendar can not show the
     *  cross date event by split one cross date event to many non
     *  cross date event
     */
    splitCrossDateEvent = (eventList)=>{
        let newEventList=new Array()
        for(let i=0;i<eventList.length;i++) {
            let event=eventList[i];
            let allDate=this.getAllDate(event.start,event.end);
           if(allDate.length==1){
               event.originId=event.id;
                event.originStart= event.start;
                   event.originEnd=event.end;
               newEventList.push(event);

           }else {
               for(let i=0;i<allDate.length;i++){
                   let date=allDate[i];
                   if(i==0){
                       let newEvent={
                           editAble: event.editAble,
                           end: date+' 23:59:00',
                           id: event.id,
                           memo: event.memo,
                           simpleUserList: event.simpleUserList,
                           start: event.start,
                           title: event.title,
                           originId: event.id,
                           originStart: event.start,
                           originEnd: event.end};
                       newEventList.push(newEvent);
                   }else if(i==allDate.length-1){
                       let newEvent={
                           editAble: event.editAble,
                           end: date+' 00:00:00',
                           id: event.id+'_'+i,
                           memo: event.memo,
                           simpleUserList: event.simpleUserList,
                           start: event.end,
                           title: event.title,
                           originId: event.id,
                           originStart: event.start,
                           originEnd: event.end};
                       if(newEvent.start!==newEvent.end){
                           newEventList.push(newEvent);
                       }

                   }else{
                       let newEvent={
                           editAble: event.editAble,
                           end: date+' 23:59:00',
                           id: event.id+'_'+i,
                           memo: event.memo,
                           simpleUserList: event.simpleUserList,
                           start: date+' 00:00:00',
                           title: event.title,
                           originId: event.id,
                           originStart: event.start,
                           originEnd: event.end};
                       newEventList.push(newEvent);
                   }
               }
           }
        }
        return newEventList;
    }

    getAllDate=(start, end)=>{
        start=start.substring(0,10);
        end=end.substring(0,10);
        //初始化日期列表，数组
        let allDateArray = new Array();
        let i=0;
        //开始日期小于等于结束日期,并循环
        while(start<=end){
            allDateArray[i] = start;
            //获取开始日期时间戳
            let startTimeSt = new Date(start).getTime();
           //增加一天时间戳后的日期
            let nextDate = startTimeSt + (24*60*60*1000);
            //拼接年月日，这里的月份会返回（0-11），所以要+1
            let nextDateY = new Date(nextDate).getFullYear()+'-';
            let nextDateM = (new Date(nextDate).getMonth()+1 < 10)?'0'+(new Date(nextDate).getMonth()+1)+'-':(new Date(nextDate).getMonth()+1)+'-';
            let nextDateD = (new Date(nextDate).getDate() < 10)?'0'+new Date(nextDate).getDate():new Date(nextDate).getDate();
            start = nextDateY+nextDateM+nextDateD;
            i++;
        }
        return allDateArray;
    }


    onPageChange = (data: OnPageChangeData) => {
        this.setState({"eventList":{}});
        axios.post('api/oa/work/event/findMyAll', Qs.stringify({
            start:moment(data.rangeFrom).format('YYYY-MM-DD HH:mm:ss'),
            end:moment(data.rangeTo).format('YYYY-MM-DD HH:mm:ss')
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{

                let  eventList=response.data.data;

                eventList=this.splitCrossDateEvent(eventList);

                let stateEventList=this.state.eventList;

                for(let i=0;i<eventList.length;i++){

                    let event=eventList[i];

                    let eventDate=moment(event.start).format('DD-MM-YYYY HH:mm:ss').substring(0,10);

                    if(stateEventList[eventDate]==undefined){
                        let newEventList=new Array()
                        stateEventList[eventDate]=newEventList;
                    }
                    let newEvent= {
                        id: event.id,
                        startAt: moment(event.start).utc().format(),
                        endAt: moment(event.end).utc().format(),
                        summary: event.title,
                        color: (new Date(event.start))>(new Date())?'green':'gray',
                        originEvent:event

                    };
                    stateEventList[eventDate].push(newEvent);
                }
                this.setState({eventList:stateEventList})
            })
            .catch(function (error) {

            });
    }

    render(){
        return(

            <Calend
                onEventClick={this.onEventClick}
                events={this.state.eventList}
                initialDate={new Date().toISOString()}
                hourHeight={60}
                initialView={CalendarView.WEEK}
                disabledViews={[CalendarView.DAY]}
                onNewEventClick={this.onNewEventClick}
                onPageChange={this.onPageChange}
                onSelectView={this.onSelectView}

            />

        );
    }
}
export default withRouter(MySchedule)